package top.yihoxu.yojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Component;
import top.yihoxu.yojcodesandbox.model.ExecuteCodeRequest;
import top.yihoxu.yojcodesandbox.model.ExecuteCodeResponse;
import top.yihoxu.yojcodesandbox.model.ExecuteMessage;
import top.yihoxu.yojcodesandbox.model.JudgeInfo;
import top.yihoxu.yojcodesandbox.template.JavaDockerCodeSandBox;
import top.yihoxu.yojcodesandbox.template.JavaNativeCodeSandBox;
import top.yihoxu.yojcodesandbox.utils.ProcessUtils;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @Author dth
 * @Date 2024/5/4 02:53
 * @PackageName:top.yihoxu.yojcodesandbox
 * @ClassName: JavaNativeCodeSandBox
 * @Description: TODO
 * @Version 1.0
 */
@Component
public class JavaNativeCodeSandBoxOld implements CodeSandbox {
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();
        List<String> inputList = executeCodeRequest.getInputList();
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + "tmpCode";
        //判断全局代码目录是否存在，没有则新建
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }
        //把用户的代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        File userCodeFile = FileUtil.writeString(code, userCodeParentPath + File.separator + "Main.java", StandardCharsets.UTF_8);

        // 2编译代码得到class 文件
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            System.out.println(executeMessage);
        } catch (Exception  e) {
            getErrorResponse(e);
        }
        //3 执行代码
        List<ExecuteMessage> executeMessageList=new ArrayList<>();
        for (String inputArgs : inputList) {
            String runCmd = String.format("java -cp %s Main %s", userCodeParentPath, inputArgs);
            try {
                Process runProcess = Runtime.getRuntime().exec(runCmd);
                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
                executeMessageList.add(executeMessage);
                System.out.println(executeMessage);
            } catch (Exception e) {
                getErrorResponse(e);
            }
        }

        //4收集整理输出结果
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        ArrayList<String> outputList = new ArrayList<>();
        long maxTime=0;
        for(ExecuteMessage executeMessage:executeMessageList){
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)){
                executeCodeResponse.setMessage(errorMessage);
                //执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            Long time = executeMessage.getTime();
            if (time!=null){
                maxTime=Math.max(maxTime,time);
            }
            outputList.add(executeMessage.getMessage());
        }
        //正常运行
        if (outputList.size()==executeMessageList.size()){
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
//        judgeInfo.setMemory();
        executeCodeResponse.setJudgeInfo(judgeInfo);

        //5文件清理
        if (userCodeFile.getParentFile()!=null){
            boolean del = FileUtil.del(userCodeFile);
            System.out.println("删除"+(del?"成功":"失败"));
        }
        return executeCodeResponse;
    }

    public static void main(String[] args) {
        JavaDockerCodeSandBox javaDockerCodeSandBox = new JavaDockerCodeSandBox();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 2","2 3"));
        String code = ResourceUtil.readStr("testCode/simpleComputeArgs/Main.java", StandardCharsets.UTF_8);
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");
        ExecuteCodeResponse executeCodeResponse = javaDockerCodeSandBox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);
    }

    /**
     * 错误异常
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e){
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        //标示代码沙箱错误
        executeCodeResponse.setStatus(2);
        return  executeCodeResponse;

    }
}
